package com.okaixz.manager.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author 陈大专
 * @time 2024/10/23 19:33
 * @des id生成类
 **/
@Slf4j
@Component
public class MyIdUtil {
    @Autowired
    public StringRedisTemplate redisTemplate;

    private static final long BEGIN_TIME_SECONDS=1729712500l;//业务开时时间秒数值 2024年10月23 32位秒数值可用68年
    private static final int START_YEAR=2025;//起始年份

    public void getTimeStramp(){
        LocalDateTime now = LocalDateTime.now();
        long beginTimeSeconds = now.toEpochSecond(ZoneOffset.UTC);
        log.info("begin:{}",beginTimeSeconds);

    }

    public long nextId(String keyprefx){
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);//当前时间秒数值
        long timStamp=nowSecond-BEGIN_TIME_SECONDS;
        log.info("timeStamp:{}",timStamp);

        String key=keyprefx+now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long sn = redisTemplate.opsForValue().increment(key);
        log.info("sn:{}",sn);

        return timStamp<<32|sn;
    }

    /**
     * 格式：当前天在一年中的天数(3位0-365)+序列号(最多long的最大值)+年份(2位00-99 从2025看开始的第几年)145100
     * 不同客户端userid也不同
     * @return
     */
    public  String getUserId(){
        LocalDateTime now = LocalDateTime.now();
        int currentYear = Year.now().getValue();
        // 计算当前为2025年以来的第几年 从第0年开始
        int yearsSince2025 = currentYear - START_YEAR;
        int dayOfYear = now.getDayOfYear();//当前天数
        String key=now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long sn = redisTemplate.opsForValue().increment(key);
        // 格式：一年中第几天(3位)+序列号(同一天中新增用户序号多少位都有可能)+年份(2位00-99)
        return String.format("%03d%s%02d",dayOfYear, sn,yearsSince2025);
    }

    // 生成日期前缀（年份后2位+当年第几天）
    private String generateDatePrefix() {
        LocalDate now = LocalDate.now();
        String year = now.format(DateTimeFormatter.ofPattern("yy"));
        int dayOfYear = now.getDayOfYear();
        return String.format("%s%03d", year, dayOfYear);
    }

    public String getDayOfYear(){
        LocalDateTime now = LocalDateTime.now();
        int dayOfYear = now.getDayOfYear();//当前天数
        return String.format("%03d", dayOfYear); // 不足3位前面补0
    }

}
